package com.android.weather1;

import java.io.IOException;
import java.io.InputStream;

import java.net.URL;
import javax.xml.parsers.SAXParser;
import java.net.MalformedURLException;
import javax.xml.parsers.SAXParserFactory;

public class RSSParser
{
	private URL urlYahoo;
	
	public RSSParser(String url)
	{
		try {
            this.urlYahoo = new URL(url);
        } 
		catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
	}
	
	public RSSParser()	{
	    this.urlYahoo = null;
 	}
	
	public WeatherYahoo parse(InputStream is) 
	{
        SAXParserFactory factory = SAXParserFactory.newInstance();
        
        try {
            SAXParser parser = factory.newSAXParser();
            RSSHandler handler = new RSSHandler();
            if (this.urlYahoo != null)
               parser.parse(this.getInputStream(), handler);  //get URL
            else
               parser.parse(is, handler); //use local asset
            
            return handler.getWeather();
        } 
        catch (Exception e) {
            throw new RuntimeException(e);
        } 
    }

	private InputStream getInputStream() 
	{
        try {
            return urlYahoo.openConnection().getInputStream();
        } 
        catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}